package redis.inaction.spring.ops;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import redis.inaction.spring.dao.CityDao;
import redis.inaction.spring.entity.City;
import redis.inaction.spring.repository.CityRedisRepository;

import java.util.Optional;

@Slf4j
public class RedisRepositoryOps {

    @Autowired
    private CityRedisRepository cityRedisRepository;

    @Autowired
    private CityDao cityDao;

    public City getCity(String code){
        Optional<City> cachedCity = cityRedisRepository.findOneByCode(code);

        if(!cachedCity.isPresent()){
            City city = cityDao.getCity(code);
            cityRedisRepository.save(city == null ? City.CITY_NULL : city);
            return city;
        }

        return City.CITY_NULL.equals(cachedCity.get()) ? null : cachedCity.get();
    }

}
